package fr.lille.inria.adam.lifl.EcoGardeInventory.Activities;

import java.util.Arrays;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RadioButton;
import fr.lille.inria.adam.lifl.EcoGardeInventory.R;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Services.LocationService;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Services.LocationService.LocationServiceBinder;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.SIGObservation;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.SIGObservation.Gender;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.sparse.SparseAdapter;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.sparse.SparseEntry;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.sparse.SparseEntryValueCompareBuilder;

public class CategorizePopulation extends BuildObservationActivity {
	protected ServiceConnection clientLocationServConn = null;
	protected boolean isClientLocationBounded = false;
	private SIGObservation observationEnCoursDeRealisation;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.select_population_genre);
		
		this.initializeSexePicker();
		this.initializeLocationServConn(); // Pr�chauffage de la localisation
	}

	@Override
	protected void onStart() {
		super.onStart();
		
		Intent locServIntent = new Intent(this, LocationService.class);
		isClientLocationBounded = bindService(locServIntent, this.clientLocationServConn, BIND_AUTO_CREATE);
		this.observationEnCoursDeRealisation = getIntent().getExtras().getParcelable("SIG_OBSERVATION");
		observationEnCoursDeRealisation.populationGender=Gender.Undefined;
	}
	
	
	@Override
	protected void onStop() {
		super.onStop();
		if (isClientLocationBounded) { unbindService(clientLocationServConn); }
	}
	
	/**Comme les bouton radio sont � l'int�rieur d'un TableLayout plut�t qu'un
	 * RadioGroup (pour des raisons purement estetique) alors le m�canismes 
	 * d'exclusion mutuelle des boutons radios disparait.
	 * 
	 * On le r�-impl�mentent ici, en plus d'ajouter les op�rations qui 
	 * param�trise l'observation en cours de r�alisation.
	 */
	private void initializeSexePicker() {
		final RadioButton[] genderBts = new RadioButton[4];
		genderBts[0] = (RadioButton) findViewById(R.id.radioUndefined);
		genderBts[1] = (RadioButton) findViewById(R.id.radioBoth);
		genderBts[2] = (RadioButton) findViewById(R.id.radioMale);
		genderBts[3] = (RadioButton) findViewById(R.id.radioFemale);
		
		for (RadioButton aBt : genderBts) {
			aBt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					final RadioButton bt = (RadioButton) v;

					for (RadioButton gBt : genderBts) gBt.setChecked(false); // On eteint tout les boutons
					bt.setChecked(true); // on allume celui qui a �t� click�
					
					// on place la valeur dans l'observation
					switch (bt.getId()) {
					case R.id.radioUndefined: observationEnCoursDeRealisation.populationGender=Gender.Undefined; break;
					case R.id.radioBoth: observationEnCoursDeRealisation.populationGender=Gender.Both; break;
					case R.id.radioMale: observationEnCoursDeRealisation.populationGender=Gender.Male; break;
					case R.id.radioFemale: observationEnCoursDeRealisation.populationGender=Gender.Female; break;
					default: Log.wtf("CategorizePop", "Click sur un radio button impr�vu", new Throwable());
						break;
					}
				}
			});
		}
	}

	/**Banale m�thode qui:
	 *  - va chercher les don�nes en base
	 *  - les tries, les adaptes
	 *  - les branches sur la ListView
	 *  - ajoute le comportement au click (ajout du comportement � la note
	 *   et changement d'Activit�)
	 */
	private void initializeComportementPicker() {
		SparseArray<String> comps = clientBinder.retrieveComportements(observationEnCoursDeRealisation.groupeEspece);
		@SuppressWarnings("unchecked")
		SparseEntry<String>[] compsArray = new SparseEntry[comps.size()];
		SparseEntry.toArray(comps, compsArray, new SparseEntryValueCompareBuilder<String>());
		Arrays.sort(compsArray);
		SparseAdapter compAdapter = new SparseAdapter(getApplicationContext(), 
				R.layout.select_listitem, 
				compsArray);
		
		final ListView compList = (ListView) findViewById(R.id.select_population_comportementListView);
		compList.setAdapter(compAdapter);
		compList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				observationEnCoursDeRealisation.comportement = (int) id;
				startNextActivity();
			}
		});
	}
	
	
	private void initializeLocationServConn() {
		/* L'envoi final est proche, nous allons pr�-chauffer le service
		 * de localisation pour augmenter la r�activit�e.
		 */
		this.clientLocationServConn = new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) { }
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				final LocationServiceBinder bind = (LocationServiceBinder) service;
				bind.turnReady();
			}
		};
	}
	
	protected ServiceConnection initializeClientSIGServConn() {
		return new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName name) { }
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				initializeComportementPicker();
			}
		};
	}

	private void startNextActivity() {
		Intent selectObsIntent = new Intent(getApplicationContext(), Finalize.class);
		selectObsIntent.putExtra("SIG_OBSERVATION", observationEnCoursDeRealisation);
		selectObsIntent.putExtra("SIG_USER", user);
		startActivity(selectObsIntent);
	}
}
